package com.runchinaup.smartbelt.activity;

import android.app.ProgressDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Handler;
import android.support.annotation.RequiresApi;
import android.support.v7.widget.LinearLayoutManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.runchinaup.runchilibrary.modes.activity.RootActivity;
import com.runchinaup.runchilibrary.utils.ViewUtil;
import com.runchinaup.smartbelt.R;
import com.runchinaup.smartbelt.ble.BlueGattCallbackHelper;
import com.runchinaup.smartbelt.domian.BleDevice;
import com.runchinaup.smartbelt.domian.BleHistoryData;
import com.runchinaup.smartbelt.preferences.BlueInfoPre;
import com.yanzhenjie.recyclerview.swipe.SwipeMenu;
import com.yanzhenjie.recyclerview.swipe.SwipeMenuBridge;
import com.yanzhenjie.recyclerview.swipe.SwipeMenuCreator;
import com.yanzhenjie.recyclerview.swipe.SwipeMenuItem;
import com.yanzhenjie.recyclerview.swipe.SwipeMenuItemClickListener;
import com.yanzhenjie.recyclerview.swipe.SwipeMenuRecyclerView;
import com.yanzhenjie.recyclerview.swipe.widget.DefaultItemDecoration;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;


/**
 * Created by liber on 2018/1/24.
 */

/**
 * 多蓝牙设备连接，BluetoothGatt可以多个,
 */
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
public class ScanActivity extends RootActivity {

    private TextView centerText;
    private ImageView leftIcon, rightIcon;
    private ListView listView;
    private SwipeMenuRecyclerView swipeMenuList;
    private ScanAdapter findAdapter;
    private HistoryAdapter historyAdapter;
    List<BluetoothDevice> findList = new ArrayList<>();         //扫描到的设备
    List<BluetoothDevice> hisHadFind = new ArrayList<>();       //点击历史连接设备时，附近是否有此设备
    ArrayList<BleHistoryData> historyListData;                  //记录历史连接过的设备
    HashSet<String> macList = new HashSet<>();                  //用于过滤扫描，历史连接中已经添加的
    HashSet<String> historyMacList = new HashSet<>();           //过滤历史连接过的列表，防止重复添加
    private ProgressDialog progressDialog;
    private BlueGattCallbackHelper gattCallbackHelper = BlueGattCallbackHelper.getBlueGattCallbackHelper();
    private String bluetoothPosition;

    @Override
    public int loadLayout() {
        return R.layout.ui_scan;
    }

    @Override
    public void initView() {
        centerText = $View(R.id.centerText);
        centerText.setText(R.string.add_drivce);

        leftIcon = $View(R.id.leftIcon);
        leftIcon.setImageResource(R.mipmap.back_white);

        rightIcon = $View(R.id.rightIcon);
        rightIcon.setImageResource(R.mipmap.refresh);

        listView = $View(R.id.blue_tooth_list);
        swipeMenuList = $View(R.id.had_link_list);

        //如果是第一次创建，可能为空.        把已经连接过的放到macList中，防止重复添加
        historyListData = BlueInfoPre.read(this);
        if (historyListData == null) {
            historyListData = new ArrayList<>();
        } else {
            addHistoryListDataToMac();
        }

        progressDialog = new ProgressDialog(this);
        progressDialog.setCancelable(false);
        progressDialog.setCanceledOnTouchOutside(false);
        progressDialog.setMessage($str(R.string.linking));

        bluetoothPosition = getIntent().getStringExtra("bluetoothPosition");

        //初始化发现设备的适配器
        initFindAdapter();
        //开始扫描
        startScan();

        initSwipeMenuRecyclerView();
        //初始化连接历史的适配器
        initHistoryAdapter();

    }

    //添加历史记录里面的设备，到过滤的数组里面
    private void addHistoryListDataToMac() {
        macList.clear();
        historyMacList.clear();
        for (int i = 0; i < historyListData.size(); i++) {
            historyMacList.add(historyListData.get(i).getAdress());
            macList.add(historyListData.get(i).getAdress());
        }
    }

    private void initSwipeMenuRecyclerView() {

        swipeMenuList.setSwipeMenuCreator(swipeMenuCreator);
        swipeMenuList.setSwipeMenuItemClickListener(listener);
        swipeMenuList.setHasFixedSize(true);
        swipeMenuList.setLayoutManager(new LinearLayoutManager(this));
        swipeMenuList.addItemDecoration(new DefaultItemDecoration(
                Color.parseColor("#999999"),
                LinearLayout.LayoutParams.MATCH_PARENT,
                ViewUtil.dip2px(1.0f)));
    }

    //侧滑菜单
    private SwipeMenuCreator swipeMenuCreator = new SwipeMenuCreator() {
        @Override
        public void onCreateMenu(SwipeMenu swipeLeftMenu, SwipeMenu swipeRightMenu, int viewType) {
            SwipeMenuItem deleteItem = new SwipeMenuItem(getUI())
                    .setBackgroundColor(Color.parseColor("#FF555B"))
                    .setText(R.string.delect)
                    .setTextColor(Color.parseColor("#FFFFFF"))
                    .setWidth(ViewUtil.dip2px(70.0f))
                    .setHeight(ViewGroup.LayoutParams.MATCH_PARENT);
            swipeRightMenu.addMenuItem(deleteItem);
        }
    };
    //监听侧滑菜单
    private SwipeMenuItemClickListener listener = new SwipeMenuItemClickListener() {
        @Override
        public void onItemClick(SwipeMenuBridge menuBridge) {

            // RecyclerView的Item的position。
            int position = menuBridge.getAdapterPosition();
            // 菜单在RecyclerView的Item中的Position。
            int menuPosition = menuBridge.getPosition();
            if (menuPosition == 0) {
                if (historyListData.get(position) != null) {
                    String mac = historyListData.get(position).getAdress();
                    macList.remove(mac);
                    historyMacList.remove(mac);
                    historyListData.remove(position);
                    menuBridge.closeMenu();
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            historyAdapter.notifyDataSetChanged();
                            findAdapter.notifyDataSetChanged();
                            BlueInfoPre.save(ScanActivity.this, historyListData);
                        }
                    });
                }
            }
        }
    };

    private void initHistoryAdapter() {
        //初始化连接历史的适配器
        historyAdapter = new HistoryAdapter<BleHistoryData>(historyListData, this) {
            @Override
            protected void setLayoutData(ThisTag thisTag, BleHistoryData bleHistoryData, int position) {
                thisTag.name.setText(bleHistoryData.getName());
                thisTag.mac.setText(bleHistoryData.getAdress());
                //获取已经连接的设备
                ArrayList<String> connectMac = gattCallbackHelper.getHadConnectBlue();
                if (connectMac.size() > 0) {
//                    Log.e("setLayoutData", connectMac.size() + "");
                    int len = connectMac.size();
                    for (int i = 0; i < len; i++) {
                        if (bleHistoryData.getAdress().equalsIgnoreCase(connectMac.get(i))) {
                            thisTag.state.setText(R.string.had_linking);        //如果已经连接则在后面加个已连接
                        }
                    }
                }
            }

            @Override
            protected void onChange(final BleHistoryData bleHistoryData) {
                //获取已经连接的设备
                ArrayList<String> connectMac = gattCallbackHelper.getHadConnectBlue();
                if (connectMac.size() > 0) {
                    for (int i = 0; i < connectMac.size(); i++) {
                        //如果连接过，就不让重复点击
                        if (bleHistoryData.getAdress().equals(connectMac.get(i))) {
                            toast(R.string.had_link_no_link_again);
                            return;
                        }
                    }
                }
                progressDialog.show();
                //5秒后（蓝牙停止扫描），扫描到的设备中没有这个设备，提示
                final Timer timer = new Timer();
                timer.schedule(new TimerTask() {
                    @Override
                    public void run() {
                        boolean hadDevice = false;
                        for (int i = 0; i < hisHadFind.size(); i++) {
                            if (hisHadFind.get(i).getAddress().equals(bleHistoryData.getAdress())) {
                                hadDevice = true;
                            }
                        }
                        if (!hadDevice) {
                            progressDialog.cancel();
                            toast(R.string.no_had_device);
                        }
                    }
                }, 5500);
                String mac = bleHistoryData.getAdress();
                BleDevice bleDevice = new BleDevice(bleHistoryData.getName(), mac);
                gattCallbackHelper.linkBle(bluetoothPosition, bleDevice, new BlueGattCallbackHelper.OnCallBackListener() {
                    @Override
                    public void linkCall(String bluetoothPosition, final BleDevice bleDevice) {
                        progressDialog.cancel();
                        Log.e("linkBle", "is Connect");
                        Intent intent = new Intent();
                        intent.putExtra("bleMac", bleDevice.getAddress());
                        setResult(333, intent);
                        timer.cancel();
                        finish();
                    }

                    @Override
                    public void onState(int state, String bluetoothPosition, BleDevice bbb) {
                        if (state == 0) {
                            progressDialog.cancel();
                            timer.cancel();
                            toast(R.string.link_disconnect);
                        }
                        if (state == 2) {
                            progressDialog.cancel();
                            timer.cancel();
                            toast(R.string.unlink);
                        }
                        if (state == 133) {
                            progressDialog.cancel();
                            timer.cancel();
                            toast(R.string.link_disconnect);
                        }
                    }

                    @Override
                    public void getElectricity(byte[] data) {

                    }

                    @Override
                    public void onExceptionDis(String bluetoothPosition, BleDevice device) {

                    }

                    @Override
                    public void getAlarmCan(byte[] data) {

                    }

                    @Override
                    public void getAlarmTime(byte[] data) {

                    }
                });
            }
        };
        swipeMenuList.setAdapter(historyAdapter);
    }

    private void initFindAdapter() {
        //初始化发现设备的适配器
        findAdapter = new ScanAdapter<BluetoothDevice>(this, findList) {
            @Override
            protected void setLayoutData(ThisTag thisTag, BluetoothDevice bluetoothDevice, int position) {
                thisTag.name.setText(bluetoothDevice.getName());
                thisTag.mac.setText(bluetoothDevice.getAddress());
            }

            @Override
            protected void onChange(BluetoothDevice scanInfo) {
                stopScan();
//                toast(R.string.linking);
                progressDialog.show();
                String mac = scanInfo.getAddress();
                BleDevice bleDevice = new BleDevice(scanInfo.getName(), mac);
                gattCallbackHelper.linkBle(bluetoothPosition, bleDevice, new BlueGattCallbackHelper.OnCallBackListener() {
                    @Override
                    public void linkCall(String bluetoothPosition, final BleDevice bleDevice) {
                        progressDialog.cancel();
                        Log.e("linkBle", "is Connect");
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                if (!historyMacList.contains(bleDevice.getAddress())) {
                                    historyListData.add(new BleHistoryData(bleDevice.getName(), bleDevice.getAddress()));
                                    historyAdapter.notifyDataSetChanged();
                                    BlueInfoPre.save(ScanActivity.this, historyListData);
                                }
                            }
                        });
                        //连接成功的设备的地址
                        Intent intent = new Intent();
                        intent.putExtra("bleMac", bleDevice.getAddress());
                        setResult(333, intent);
                        finish();
                    }

                    @Override
                    public void onState(int state, String bluetoothPosition, BleDevice bleDevice) {
                        if (state == 0) {
                            progressDialog.cancel();
                            toast(R.string.link_disconnect);
                        }
                        if (state == 2) {
                            progressDialog.cancel();
                            toast(R.string.unlink);
                        }
                        if (state == 3) {
                            progressDialog.cancel();
                            toast(R.string.link_disconnect);
                        }
                    }

                    @Override
                    public void getElectricity(byte[] data) {

                    }

                    @Override
                    public void onExceptionDis(String bluetoothPosition, BleDevice device) {

                    }

                    @Override
                    public void getAlarmCan(byte[] data) {

                    }

                    @Override
                    public void getAlarmTime(byte[] data) {

                    }

                });
            }
        };
        listView.setAdapter(findAdapter);
    }

    @Override
    public void onLeftClick(View view) {
        finish();
    }

    @Override
    public void onRightClick(View view) {
        toast(R.string.refresh_blue);
        addHistoryListDataToMac();
        startScan();
    }

    private void startScan() {
        findList.clear();
        findAdapter.notifyDataSetChanged();
        scanBlueLow();
    }

    private void stopScan() {
        bluetoothAdapter.stopLeScan(leScanCallback);
    }

    //4.3-5.0版本
    private void scanBlueLow() {
        bluetoothAdapter.stopLeScan(leScanCallback);
        bluetoothAdapter.startLeScan(leScanCallback);

        //5秒后停止扫描
        Handler handler = new Handler();
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                stopScan();
            }
        }, 5000);
    }


    //低版本的扫描回调
    final BluetoothAdapter.LeScanCallback leScanCallback = new BluetoothAdapter.LeScanCallback() {
        @Override
        public void onLeScan(final BluetoothDevice device, int rssi, byte[] scanRecord) {
            // device 就是扫描到的蓝牙对象，里面各种跟蓝牙有关的信息
            // rssi信号强度，这个值是个负数，范围一般为0到-100，负数越大，代表信号越弱，一般如果超过-90，连接会出现不理想的情况
            // scanRecord广播数据，里面的数据就是蓝牙设备希望手机在连接它之前，让手机知道的信息

            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    String name = device.getName();
                    if (TextUtils.isEmpty(name))
                        return;
                    if (!macList.contains(device.getAddress())) {
                        if (name.equals("ZNCP")) {
                            macList.add(device.getAddress());
                            findList.add(device);
                            findAdapter.notifyDataSetChanged();
                        }
                    } else {
                        if (name.equals("ZNCP")) {
                            if (!hisHadFind.contains(device)) {
                                hisHadFind.add(device);
                            }
                        }
                    }
                }

            });
        }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        stopScan();
    }
}
